<?php

namespace App\Http\Controllers\Mp;

use App\Http\Resources\Mp\UserResource;
use App\Models\BookRule;
use App\Services\BookOrderService;
use Illuminate\Http\Request;

/**
 * Class UserController
 * @package App\Http\Controllers\Mp
 * @author zjw
 */
class UserController extends BaseController
{
    public function index()
    {
        return new UserResource(\Auth::user());
    }

    public function store(Request $request) {
        $user = \Auth::user();
        $query = BookRule::where([
            ['school_id',$user->school_id],
            ['eat_date',">=",now()->addDay(1)->format("Y-m-d")],
            ['is_cancel', BookRule::NOT_CANCELED],
            ['is_settled', BookRule::NOT_SETTLED]
        ]);
        // 早餐变为自动
        if(intval($request->morning_rule) === 1) {
            $bookRules = $query->isBreakfast()->get();
        }
        // 午餐变为自动
        if(intval($request->lunch_rule) === 1) {
            $bookRules = $query->isLunch()->get();
        }
        // 晚餐变为自动
        if(intval($request->dinner_rule) === 1) {
            $bookRules = $query->isDinner()->get();
        }
        if(isset($bookRules)){
            foreach ($bookRules as $bookRule) {
                if($bookRule->isActive && $user->canBookByRule($bookRule)){
                    BookOrderService::generateOrder($user, $bookRule);
                }
            }
        }
        $user->fill($request->all());
        $user->save();
        return new UserResource(\Auth::user());
    }
}
